package cn.tk.exception;

import cn.tk.model.pojo.ResultError;
import cn.tk.model.pojo.ResultModel;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.HttpMediaTypeException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.util.Objects;

/**
 * Created by denglw on 2017/12/6.<br>
 * Desc: 全局异常处理器
 */
@ControllerAdvice
public class DefaultExceptionHandler {
    /**
     * 资源未找到异常处理<br/>
     */
    @ExceptionHandler(NotFoundException.class)
    public ResponseEntity<ResultModel<?>> notFoundException(Exception e) {
        e.printStackTrace();
        ResultError error = ResultError.NOT_FOUND;
        String message = e.getMessage();
        if (message != null) {
            error.setMessage(message);
        }
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ResultModel.failure(error));
    }

    /**
     * 坏请求异常处理<br/>
     */
    @ExceptionHandler({ HttpRequestMethodNotSupportedException.class, BadRequestException.class,
            HttpMediaTypeException.class, HttpMediaTypeNotSupportedException.class})
    public ResponseEntity<ResultModel<?>> badRequestException(Exception e) {
        e.printStackTrace();
        ResultModel<Object> failure = ResultModel.failure(ResultError.BAD_REQUEST);
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(failure);
    }

    /**
     * 常规业务异常处理<br/>
     */
    @ExceptionHandler({CustomException.class})
    public ResponseEntity<ResultModel<?>> customException(CustomException e) {
        ResultError error = ResultError.CUSTOM_ERR;
        if (e.getMessage() != null) {
            error.setMessage(e.getMessage());
        }
        if (!Objects.equals(0, e.getCode())) {
            error.setCode(e.getCode());
        }
        return ResponseEntity.status(HttpStatus.OK).body(ResultModel.failure(error));
    }

    /**
     * 服务器内部错误处理<br/>
     */
    @ExceptionHandler(Throwable.class)
    public ResponseEntity<ResultModel<?>> internalServerError(Throwable e) {
        e.printStackTrace();
        ResultModel<Object> failure = ResultModel.failure(ResultError.INTERNAL_ERR);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(failure);
    }

}
